package db.logging;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class AppenderASync implements Appender {

	Appender simpleAppender;
	BlockingQueue<String> bq = new LinkedBlockingQueue<String>();
	ExecutorService executor = Executors.newSingleThreadExecutor();

	public AppenderASync(Appender simpleAppender) {
		this.simpleAppender = simpleAppender;
		executor.execute(new RunLogger());
		executor.shutdown();
	}

	public void store(String str) {
		bq.add(str);
	}

	class RunLogger implements Runnable {
		boolean isShutdown = false;
		String message;

		public void run() {
			while (!isShutdown) {
				try {
					message = bq.take();
					simpleAppender.store(message);
					if (message.contains("SHUTDOWN")) {
						simpleAppender.store("SHUTDOWN processing ...");
						isShutdown = true;
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			simpleAppender.store("Log thread is over");
		}
	}
}
